package com.supermarket.api.service.impl;

import com.supermarket.api.bean.category.ProductReq;
import com.supermarket.api.common.Constants;
import com.supermarket.api.entity.CategoryEntity;
import com.supermarket.api.entity.ProductEntity;
import com.supermarket.api.repository.CategoryRepository;
import com.supermarket.api.repository.ProductRepository;
import com.supermarket.api.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分类服务层
 * @author 李其伟
 * @date 2023/10/17
 */
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private ProductRepository productRepository;

    @Override
    public List<CategoryEntity> list() {
        return categoryRepository.findAllByPublishStatusOrderBySortDesc(Constants.PUBLISH_STATUS_UP);
    }

    @Override
    public Page<ProductEntity> product(ProductReq req) {

        /**
         * 排序方式
         * 1 综合排序（默认） 2 销量排序 3 价格升序 4 价格降序
         * 一定要是实体类的属性，而不能是数据库的字段
         */
        Sort sort = Sort.by(Sort.Direction.DESC, "sort");
        switch (req.getType()){
            case 2:
                sort = Sort.by(Sort.Direction.DESC, "sale");
                break;
            case 3:
                sort = Sort.by(Sort.Direction.ASC, "price");
                break;
            case 4:
                sort = Sort.by(Sort.Direction.DESC, "price");
                break;
            default:
        }

        /**
         * 当前页， 每页记录数， 排序方式
         */
        Pageable pageable = PageRequest.of(req.getPageNum() , req.getPageSize(), sort);

        return productRepository.findAllByCategoryIdAndPublishStatus(req.getCategoryId(), Constants.PUBLISH_STATUS_UP,pageable);
    }

}
